from fastapi import APIRouter, UploadFile, File, Form, HTTPException, Query
from fastapi.responses import JSONResponse
from typing import Optional
from pydantic import BaseModel

from app.services.video_upload_service import VideoUploadService

router = APIRouter(prefix="/api/v1", tags=["视频管理"])

# 请求模型
class VideoUploadRequest(BaseModel):
    original_language: Optional[str] = None
    target_language: Optional[str] = None
    description: Optional[str] = None

# 响应模型
class VideoResponse(BaseModel):
    success: bool
    message: str
    video_id: Optional[str] = None
    video_info: Optional[dict] = None

class VideoListResponse(BaseModel):
    success: bool
    videos: list
    total: int
    limit: int
    offset: int

# 创建服务实例
video_service = VideoUploadService()

@router.post("/videos/upload", response_model=VideoResponse)
async def upload_video(
    file: UploadFile = File(...),
    original_language: Optional[str] = Form(None),
    target_language: Optional[str] = Form(None),
    description: Optional[str] = Form(None)
):
    """
    上传视频文件
    
    - **file**: 视频文件 (支持格式: mp4, avi, mov, mkv, wmv, flv, webm, m4v)
    - **original_language**: 原始语言代码 (可选)
    - **target_language**: 目标语言代码 (可选)
    - **description**: 视频描述 (可选)
    """
    try:
        result = await video_service.upload_video(
            file=file,
            original_language=original_language,
            target_language=target_language,
            description=description
        )
        return JSONResponse(content=result)
    except HTTPException as e:
        return JSONResponse(
            status_code=e.status_code,
            content={"success": False, "message": e.detail}
        )

@router.post("/videos/{video_id}/extract-audio", response_model=VideoResponse)
async def extract_audio(video_id: str):
    """
    从视频中提取音频
    
    - **video_id**: 视频ID
    """
    try:
        result = video_service.extract_audio_from_video(video_id)
        return JSONResponse(content=result)
    except HTTPException as e:
        return JSONResponse(
            status_code=e.status_code,
            content={"success": False, "message": e.detail}
        )

@router.get("/videos/{video_id}", response_model=VideoResponse)
async def get_video_info(video_id: str):
    """
    获取视频信息
    
    - **video_id**: 视频ID
    """
    try:
        result = video_service.get_video_info(video_id)
        return JSONResponse(content=result)
    except HTTPException as e:
        return JSONResponse(
            status_code=e.status_code,
            content={"success": False, "message": e.detail}
        )

@router.get("/videos", response_model=VideoListResponse)
async def list_videos(
    limit: int = Query(10, ge=1, le=100, description="每页数量"),
    offset: int = Query(0, ge=0, description="偏移量")
):
    """
    获取视频列表
    
    - **limit**: 每页数量 (1-100)
    - **offset**: 偏移量
    """
    try:
        result = video_service.list_videos(limit=limit, offset=offset)
        return JSONResponse(content=result)
    except HTTPException as e:
        return JSONResponse(
            status_code=e.status_code,
            content={"success": False, "message": e.detail}
        )

@router.delete("/videos/{video_id}", response_model=VideoResponse)
async def delete_video(video_id: str):
    """
    删除视频
    
    - **video_id**: 视频ID
    """
    try:
        result = video_service.delete_video(video_id)
        return JSONResponse(content=result)
    except HTTPException as e:
        return JSONResponse(
            status_code=e.status_code,
            content={"success": False, "message": e.detail}
        )

@router.get("/health")
async def health_check():
    """健康检查接口"""
    return {"status": "healthy", "message": "视频翻译平台运行正常"} 